import axios, { AxiosError, AxiosRequestConfig } from 'axios'

const getToken = () => {
    const token = localStorage.getItem('token') || ''
    console.log('token=', token)
    return token || ''
}
export const netApi = axios.create({
    baseURL: import.meta.env.VITE_BASE_API || '',
    withCredentials: true,
    timeout: 30000,
})

netApi.interceptors.request.use((config) => {
    if (getToken()) {
        config.headers['X-Token'] = getToken()
    }
    return config
})

netApi.interceptors.response.use(response => {
    const { code, data } = response.data
    if (code === 200) {
        return data
    } else if (code === 2001) {
        console.log('未登录 登录失效')
    }
    return response
}, err => {
    console.log('接口信息报错', err)
})

export const net = (uc: any, config = {}): any => {
    const _config = {
        ...config,
        axios: {
            headers: {
                token: getToken()
            }
        }
    }
    let obj = {}
    obj = Object.assign(obj, uc, _config.axios, {
        $frontConfig: _config,
      })
    return netApi(obj)
}